<template>
	<view class="home">
		<custom-navbar title="个人信息" :show-back="true" @back="handleBack" />

		<view class="content" :style="{ paddingTop: navBarHeight + 'px' }">
			<view class="p30">
				<view class="formdata p4030">
					<view class="form-title mb45">基本信息</view>
					<up-form label-position="left" :model="formData" :rules="rules" ref="formRef">
						<!-- 真实姓名 -->
						<up-form-item label="真实姓名" prop="name" :borderBottom="true" :required="true" labelWidth="180">
							<up-input v-model="formData.name" placeholder="请输入真实姓名" border="none" clearable
								inputAlign="right"></up-input>
						</up-form-item>

						<!-- 性别 -->
						<up-form-item label="性别" prop="gender" :borderBottom="true" :required="true" labelWidth="180">
							<view class="radio-group-wrapper">
								<up-radio-group v-model="formData.gender" placement="row" @change="groupChange">
									<up-radio v-for="(item, index) in genderOptions" :key="index" :label="item.name"
										:name="item.value" :customStyle="{
                      marginLeft: index > 0 ? '40rpx' : '0',
                      marginBottom: '0'
                    }"></up-radio>
								</up-radio-group>
							</view>
						</up-form-item>

						<!-- 出生日期 -->
						<up-form-item label="出生年月日" prop="birth_date" :borderBottom="true" :required="true"
							labelWidth="180" @click="openPickerdData('date')">
							<up-input v-model="formData.birth_date" inputAlign="right" disabled disabledColor="#ffffff"
								placeholder="请选择出生日期" border="none" @click="datePickerValue = true"></up-input>
							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<!-- 籍贯 -->
						<up-form-item label="籍贯" prop="domicile" :borderBottom="true" :required="true" labelWidth="180"
							@click="openRegionPicker('domicile')">
							<up-input v-model="formData.domicile" placeholder="请选择籍贯" border="none" disabled
								disabledColor="#ffffff" inputAlign="right"></up-input>
							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<!-- 现居住地 -->
						<up-form-item label="现居住地" prop="current_residence" :borderBottom="true" :required="true"
							labelWidth="180">
							<up-input v-model="formData.current_residence" placeholder="请输入现居住地" border="none" clearable
								inputAlign="right"></up-input>
						</up-form-item>

						<!-- 学历 -->
						<up-form-item label="学历" prop="education_level" :borderBottom="true" :required="true"
							labelWidth="180" @click="educationShow = true">
							<up-input v-model="formData.education_level" placeholder="请选择学历" border="none" disabled
								disabledColor="#ffffff" inputAlign="right"></up-input>
							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<!-- 毕业学校 -->
						<up-form-item label="毕业学校" prop="graduation_school" :borderBottom="true" :required="true"
							labelWidth="180">
							<up-input v-model="formData.graduation_school" placeholder="请输入毕业学校" border="none" clearable
								inputAlign="right"></up-input>
						</up-form-item>

						<!-- 英语水平 -->
						<up-form-item label="英语水平" prop="english_level" :borderBottom="true" :required="true"
							labelWidth="180" @click="openEnglishPicker('english')">
							<up-input v-model="formData.english_level" placeholder="请选择英语水平" border="none" disabled
								disabledColor="#ffffff" inputAlign="right"></up-input>
							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<!-- 求职意向 -->
						<up-form-item label="求职意向" prop="career_intention" :borderBottom="true" :required="true"
							labelWidth="180">
							<up-input v-model="formData.career_intention" placeholder="请输入求职意向" border="none" clearable
								inputAlign="right"></up-input>
						</up-form-item>

						<!-- 联系电话 -->
						<up-form-item label="联系电话" prop="contact_number" :borderBottom="true" :required="true"
							labelWidth="180">
							<up-input v-model="formData.contact_number" placeholder="请输入联系电话" border="none" clearable
								inputAlign="right" type="number"></up-input>
						</up-form-item>

						<!-- 邮箱 -->
						<up-form-item label="邮箱" prop="email" :borderBottom="true" :required="true" labelWidth="180">
							<up-input v-model="formData.email" placeholder="请输入邮箱" border="none" clearable
								inputAlign="right"></up-input>
						</up-form-item>
					</up-form>
				</view>

				<up-button type="primary" text="更新我的简历" :loading="submitting" @click="handleSubmit"
					customStyle="border-radius:10rpx;margin-top:40rpx;"></up-button>
			</view>
		</view>

		<!-- 日期选择器 -->
		<up-datetime-picker v-model="datePickerValue" :show="datePickerShow" mode="date" :minDate="minDate"
			:maxDate="maxDate" @confirm="handleDateConfirm" @cancel="datePickerShow = false"></up-datetime-picker>
		<!-- 地区选择器 -->
		<up-picker :columns="regionColumns" :show="show" v-model="showRegionPicker" @change="handleRegionChange"
			@confirm="handleRegionConfirm" @cancel="show = false" :defaultIndex="regionDefaultIndex"></up-picker>
		<!-- 学历选择 -->
		<up-picker :columns="educationOptions" v-model="educationData" :show='educationShow'
			@confirm="handleEducationConfirm" placeholder="请选择学历">
		</up-picker>
		<!-- 添加英语水平选择器组件 -->
		<up-picker :columns="englishLevelOptions" v-model="englishData" :show="englishShow"
			@confirm="handleEnglishConfirm" @cancel="englishShow = false" placeholder="请选择英语水平">
		</up-picker>
	</view>
</template>

<script setup>
	import CustomNavbar from '@/components/custom-navbar.vue'
	import {
		ref,
		onMounted,
		computed,
		nextTick
	} from 'vue';
	import {
		information,
		talentdata
	} from '@/api/talents'
	import {
		getAddressSelect
	} from '@/api/user'
	import {
		getClassification
	} from '@/api/login'

	// 系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)
	const education = ref([])
	const data16 = ref([])
	const loading = ref(false)
	const educationOptions = ref([

	])
	const educationShow = ref(false)
	const educationData = ref("")
	// 处理学历数据
	const processEducationData = (data) => {
		// 将原始数据转换为需要的格式
		console.log(data)
		return [data.map(item => item.label)]

	}
	// 并行请求
	const fetchData = async () => {
		try {
			loading.value = true

			const [res14, res16, res19] = await Promise.all([
				getClassification(12),
				getClassification(''),
				getClassification(19) // 19是英语等级分类
			])

			education.value = res14.data
			educationOptions.value = processEducationData(education.value)
			data16.value = res16.data
			// 新增：处理英语等级数据
			if (res19.data && res19.data.length > 0) {
				// 将接口返回的数据转换为 picker 需要的格式
				englishLevelOptions.value = [res19.data.map(item => item.label)]
			} else {
				// 如果接口没数据，使用备用数据
				englishLevelOptions.value = [
					['无', '4级', '6级', '专四', '专八', '雅思', '托福', '其他']
				]
			}
		} catch (error) {
			console.error('请求失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
			// 如果接口报错，使用备用数据
			englishLevelOptions.value = [
				['无', '4级', '6级', '专四', '专八', '雅思', '托福', '其他']
			]
		} finally {
			loading.value = false
		}
	}


	// 表单相关
	const formRef = ref(null)
	const submitting = ref(false)
	const datePickerValue = ref('')
	const datePickerShow = ref(false)
	const showRegionPicker = ref(false)
	const maxDate = new Date().getTime() // 确保这是有效的时间戳
	const minDate = new Date('1900-01-01').getTime() // 最小可选1900年
	const show = ref(false);
	const englishShow = ref(false)
	const englishData = ref("")
	// 地区选择器相关
	const regionColumns = ref([
		[],
		[]
	]) // 省、市两级数据
	const regionDefaultIndex = ref([0, 0]) // 默认选中项
	const currentRegionField = ref('') // 当前正在编辑的地区字段
	const selectedProvince = ref(null) // 当前选中的省份
	// 存储完整的地区数据
	const regionData = ref({
		provinces: [],
		cities: []
	})
	// 表单数据
	const formData = ref({
		name: '', // 姓名
		gender: '', // 性别 1:男 2:女
		birth_date: '', // 出生年月 (格式: "1998年2月23日")
		domicile: '', // 籍贯
		current_residence: '', // 现居地
		education_level: '', // 学历
		graduation_school: '', // 毕业院校
		english_level: '', // 英语等级 (格式: "4级")
		career_intention: '', // 求职意向
		contact_number: '', // 联系电话
		email: '' // 邮箱
	})

	// 选项数据
	const genderOptions = ref([{
			name: '男',
			value: 1
		},
		{
			name: '女',
			value: 2
		}
	])


	const englishLevelOptions = ref([

	])

	// 校验规则
	const rules = {
		name: [{
				required: true,
				message: '请输入真实姓名',
				trigger: 'blur'
			},
			{
				min: 2,
				max: 10,
				message: '姓名长度为2-10个字符',
				trigger: 'blur'
			}
		],
		// gender: [{
		// 	required: true,
		// 	message: '请选择性别',
		// 	trigger: 'change'
		// }],
		birth_date: [{
			required: true,
			message: '请选择出生日期',
			trigger: 'change'
		}],
		domicile: [{
			required: true,
			message: '请输入籍贯',
			trigger: 'blur'
		}],
		current_residence: [{
			required: true,
			message: '请输入现居住地',
			trigger: 'blur'
		}],
		education_level: [{
			required: true,
			message: '请选择学历',
			trigger: 'change'
		}],
		graduation_school: [{
			required: true,
			message: '请输入毕业学校',
			trigger: 'blur'
		}],
		english_level: [{
			required: true,
			message: '请选择英语水平',
			trigger: 'change'
		}],
		career_intention: [{
			required: true,
			message: '请输入求职意向',
			trigger: 'blur'
		}],
		contact_number: [{
				required: true,
				message: '请输入联系电话',
				trigger: 'blur'
			},
			{
				pattern: /^1[3-9]\d{9}$/,
				message: '请输入正确的手机号码',
				trigger: 'blur'
			}
		],
		email: [{
				required: true,
				message: '请输入邮箱',
				trigger: 'blur'
			},
			{
				type: 'email',
				message: '请输入正确的邮箱格式',
				trigger: 'blur'
			}
		]
	}

	// 方法
	const handleBack = () => {
		uni.navigateBack()
	}

	const groupChange = (value) => {
		formData.value.gender = value
	}



	const handleEducationConfirm = (e) => {
		const selectedLabel = e.value[0]
		const selectedItem = education.value.find(item => item.label === selectedLabel)

		if (selectedLabel) {
			formData.value.education_level = selectedLabel
			educationData.value = selectedLabel // 同步到 picker 的 v-model
			console.log('已选择学历:', formData.value.education_level)
		}

		educationShow.value = false
	}


	// 打开英语选择器
	const openEnglishPicker = () => {
		englishShow.value = true
	}
	// 添加英语水平确认处理方法：
	const handleEnglishConfirm = (e) => {
		const selectedLabel = e.value[0]
		if (selectedLabel) {
			formData.value.english_level = selectedLabel
			englishData.value = selectedLabel
		}
		englishShow.value = false
	}
	// 打开日期选择器 
	const openPickerdData = () => {
		datePickerValue.value = new Date().toISOString().split('T')[0]
		datePickerShow.value = true
	}
	// 日期确认
	const handleDateConfirm = (e) => {
		const date = new Date(e.value)
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		formData.value.birth_date = `${year}年${month}月${day}日`
		datePickerShow.value = false
	}
	// 打开地区选择器
	const openRegionPicker = async (field) => {
		currentRegionField.value = field

		try {
			// 如果尚未加载省份数据，则先加载
			if (regionData.value.provinces.length === 0) {
				await initRegionData()
			}

			// 设置默认选中项
			let provinceIndex = 0
			let cityIndex = 0

			// 处理已保存的地址
			if (formData.value[field]) {
				const [savedProvince, savedCity] = formData.value[field].split(' ')
				const foundProvinceIndex = regionData.value.provinces.findIndex(
					p => p.label === savedProvince
				)

				if (foundProvinceIndex >= 0) {
					provinceIndex = foundProvinceIndex
					await loadCities(regionData.value.provinces[provinceIndex].value)

					// 查找匹配的城市
					if (savedCity) {
						const foundCityIndex = regionData.value.cities.findIndex(
							c => c.label === savedCity
						)
						if (foundCityIndex >= 0) {
							cityIndex = foundCityIndex
						}
					}
				}
			}

			regionDefaultIndex.value = [provinceIndex, cityIndex]
			show.value = true

		} catch (error) {
			console.error('打开地区选择器失败:', error)
			uni.showToast({
				title: '加载地区数据失败',
				icon: 'none'
			})
		}
	}

	// 地区选择变化事件
	const handleRegionChange = async (e) => {
		const {
			columnIndex,
			index
		} = e

		// 只处理省份列的变化
		if (columnIndex === 0) {
			const selectedProvince = regionData.value.provinces[index]
			if (selectedProvince) {
				// 显示加载状态
				regionColumns.value[1] = ['加载中...']
				await nextTick()

				// 加载新选择的省份对应的城市
				await loadCities(selectedProvince.value)

				// 重置城市选中项
				regionDefaultIndex.value = [index, 0]
			}
		}
	}
	// 初始化地区数据
	const initRegionData = async () => {
		try {
			// 加载省份数据
			const provinces = await getRegionData(1)
			regionData.value.provinces = provinces

			// 初始化地区选择器列
			regionColumns.value = [
				provinces.map(p => p.label),
				['正在加载...'] // 初始占位
			]

			// 默认加载第一个省份的市级数据
			if (provinces.length > 0) {
				await loadCities(provinces[0].value)
			}
		} catch (error) {
			console.error('初始化地区数据失败:', error)
			regionColumns.value = [
				[],
				['加载失败']
			]
		}
	}
	// 加载城市数据
	const loadCities = async (provinceCode) => {
		try {
			regionColumns.value[1] = ['加载中...'] // 加载状态提示
			const cities = await getRegionData(2, provinceCode)
			regionData.value.cities = cities
			regionColumns.value[1] = cities.map(c => c.label)

			// 如果当前正在显示选择器，强制更新视图
			if (show.value) {
				await nextTick()
			}
		} catch (error) {
			console.error('加载城市数据失败:', error)
			regionColumns.value[1] = ['加载失败']
			regionData.value.cities = []
		}
	}

	// 确认选择地区
	// 确认选择地区
	const handleRegionConfirm = (e) => {
		try {
			console.log('地区选择确认事件:', e)

			// 解构出需要的数据
			const {
				value: selectedLabels,
				index: selectedIndexes
			} = e

			// 确保数据有效
			if (!selectedLabels || selectedLabels.length < 1) {
				console.error('无效的地区选择数据')
				return
			}

			// 获取选中的省份和城市
			const selectedProvince = selectedLabels[0]
			const selectedCity = selectedLabels.length > 1 ? selectedLabels[1] : ''

			// 构建完整地址
			const fullAddress = selectedCity ?
				`${selectedProvince} ${selectedCity}` :
				selectedProvince

			// 更新表单数据
			formData.value[currentRegionField.value] = fullAddress

			// 关闭选择器
			show.value = false

			console.log('已选择地区:', fullAddress)

		} catch (error) {
			console.error('确认地区选择时出错:', error)
			uni.showToast({
				title: '选择地区失败',
				icon: 'none'
			})
		}
	}
	// 获取地区数据
	const getRegionData = async (level, parent_code = '') => {
		try {
			const res = await getAddressSelect(level, parent_code)
			if (res.code === 200) {
				console.log(res.data, 111)
				return res.data.map(item => ({
					label: item.label,
					value: item.value.toString(),
					level: item.level,
					parent_code: item.parent_code.toString()
				}))

			}
			return []
		} catch (error) {
			console.error('获取地区数据失败:', error)
			uni.showToast({
				title: '获取地区数据失败',
				icon: 'none'
			})
			return []
		}
	}

	// 提交表单
	const handleSubmit = async () => {
		try {
			submitting.value = true
			const valid = await formRef.value.validate()
			if (valid) {
				// 直接使用 formData.value，因为字段名已经与后端一致
				const res = await information(formData.value)
				uni.showToast({
					title: '更新成功',
					icon: 'success',
					duration: 1500,
					success: () => {
						// Toast显示完成后跳转
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/resume/index'
							})
						}, 1500)
					}
				})
			}
		} catch (error) {
			console.error('提交失败:', error)
			uni.showToast({
				title: error.message || '提交失败',
				icon: 'none'
			})
		} finally {
			submitting.value = false
		}
	}

	// 初始化数据
	onMounted(async () => {
		// 初始化地区数据
		await initRegionData()
		await fetchData()
		try {
			const res = await talentdata()
			if (res.data.data) {
				// 映射字段名
				const data = res.data.data
				formData.value = {
					name: data.member_name || '',
					gender: data.gender ? Number(data.gender) : null, // 确保转换为数字
					birth_date: data.birth_date || '',
					domicile: data.domicile || '',
					current_residence: data.current_residence || '',
					education_level: data.education_level || '',
					graduation_school: data.graduation_school || '',
					english_level: data.english_level || '',
					career_intention: data.career_intention || '',
					contact_number: data.contact_number || '',
					email: data.email || ''
				}
				Object.keys(formData.value).forEach(key => {
					if (res.data.data[key] !== undefined) {
						formData.value[key] = res.data.data[key]
						// 特殊处理birth_date
						// 设置日期选择器默认值
						if (data.birth_date) {
							const match = data.birth_date.match(/(\d+)年(\d+)月(\d+)日/)
							if (match) {
								datePickerValue.value = new Date(match[1], match[2] - 1, match[3])
									.toISOString()
							}
						}
					}
				})
			}
		} catch (error) {
			console.error('获取个人信息失败:', error)
			uni.showToast({
				title: '获取个人信息失败',
				icon: 'none'
			})
		}
	})
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		min-height: 100vh;
		background-color: #f7f8fa;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 70rpx);

			.p30 {
				padding: 30rpx;

				.formdata {
					width: 100%;
					background: #FFFFFF;
					border-radius: 20rpx;
					margin-bottom: 40rpx;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

					.form-title {
						font-size: 30rpx;
						font-weight: bold;
						color: #333;
					}

					::v-deep .u-form-item {
						height: 90rpx;
					}

					.radio-group-wrapper {
						display: flex;
						justify-content: flex-end;
						width: 100%;
						padding-right: 20rpx;

						::v-deep .u-radio-group {
							display: flex;
							flex-direction: row;
							align-items: center;
						}

						::v-deep .u-radio {
							display: flex;
							align-items: center;
						}

						::v-deep.u-radio-group {
							flex: none;
						}
					}
				}
			}
		}
	}
</style>